package io.github.starwishsama.comet.utils

import com.google.gson.JsonParser
import io.github.starwishsama.comet.utils.URIComponent.encodeURIComponent

object urlShorten {
    private val hostname = arrayOf("danbooru.donmai.us", "konachan.com", "yande.re")

    fun confuseURL(url: String): String {
        val path: String
        val match = hostname.filter { url.contains(it, ignoreCase = true) }
        if (match.isNotEmpty()) {
            path = shorten(url)
            return "https://j.loli.best/#${path}"
        }
        return pixivShorten(url);
    }

    private fun shorten(url:String):String {
        val request = NetUtil.doHttpRequestGet(
            "https://is.gd/create.php?format=simple&url=${encodeURIComponent(url)}",
            5000
        )
        val result = request.executeAsync()
        val path: String
        val body = result.body()
        try {
            val resultBody = JsonParser.parseString(body)
            val resultJson = resultBody.asJsonObject["results"].asJsonArray[0].asJsonObject
            path = resultJson["header"].asJsonObject["thumbnail"].asString
        } catch (e: Exception){
            return "${e.message}"
        }
        return path
    }

    fun pixivShorten(url:String):String {
        val pidSearch = Regex("""/ pixiv.+ illust_id =([0 - 9] +) / . exec (url) || / pixiv . + artworks\/([0-9]+)/.exec(url)""").findAll("1234567890")
        val pidResult = StringBuilder()
        for (matchedText in pidSearch) {
            pidResult.append(matchedText.value + " ")
        }
        if (pidResult.isNotBlank()) {
            return "https://pixiv.net/i/${pidResult}"
        }
        val uidSearch = Regex("""/ pixiv.+ member \.php\?id = ([0-9]+)/.exec(url) || /pixiv.+users\/([0-9]+)/.exec(url)""").findAll("1234567890")
        val uidResult = StringBuilder()
        for (matchedText in uidSearch) {
            uidResult.append(matchedText.value + " ")
        }
        if (uidResult.isNotBlank()) {
            return "https://pixiv.net/u/${uidResult}"
        }
        return url;
    }
}